<?php

namespace App\Http\Controllers;

use App\Models\Project;
use App\Models\User;
use App\Services\UserService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class UserController extends Controller
{
    protected $UserService;
    public function __construct(UserService $UserService)
    {
        $this->UserService = $UserService;
    }

    public function login(Request $Request)
    {
        $Request->validate([
            'mobile' => 'required|max:255',
            'password' => 'required|min:6',
        ]);

        $user = User::with('role')->with('projects')->where('mobile',$Request->mobile)->first();
        if(!$user){
            return response()->json(['code' => '404', 'msg' => '用户不存在']);
        }
        if(!$user->validateForPassportPasswordGrant($Request->password)){
            return response()->json(['code' => '404', 'msg' => '密码错误']);
        }
        $token = $user->createToken('api')->accessToken;
        $project = new Project();
        foreach ($user->projects as $key => $value) {
            $user->projects[$key]->remainDuration = $project->remainDuration($value->end_date);
            $user->projects[$key]->duration = $project->duration($value->start_date,$value->end_date);
        }
        return response()->json(['code' => '200', 'msg' => '登录成功','user'=>$user,'token'=>$token]);
    }

    public function index() {
        $data = Auth::user();
        $data->role;
        return response()->json(['code' => '200', 'msg' => '操作成功','data'=>$data]);
    }
}
